<template>
  <div>
    <div class="page-header">
      <h1>新增文章</h1>
      <el-button @click="goBack">返回列表</el-button>
    </div>
    
    <!-- 文章表单 -->
    <el-card class="form-card" shadow="never">
      <el-form 
        :model="articleForm" 
        :rules="formRules" 
        ref="articleFormRef" 
        label-width="120px"
        class="article-form"
      >
        
        <el-form-item label="文章标题" prop="title">
          <el-input 
            v-model="articleForm.title" 
            placeholder="请输入文章标题" 
            maxlength="100"
            show-word-limit
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item label="文章简介" prop="summary">
          <el-input 
            v-model="articleForm.summary" 
            type="textarea"
            placeholder="请输入文章简介"
            :rows="3"
            maxlength="300"
            show-word-limit
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item label="文章类型" prop="type">
          <el-radio-group v-model="articleForm.type">
            <el-radio value="text">纯文章</el-radio>
            <el-radio value="audio">音频文章</el-radio>
            <el-radio value="video">视频文章</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 音频上传区域 -->
        <el-form-item 
          label="音频文件" 
          prop="audioUrl"
          v-if="articleForm.type === 'audio' || articleForm.type === 'video'"
        >
          <div class="upload-section">
            <el-upload
              ref="audioUploadRef"
              class="upload-demo"
              drag
              :auto-upload="false"
              :on-change="handleAudioChange"
              :before-upload="beforeAudioUpload"
              accept="audio/*"
              :limit="1"
              :file-list="audioFileList"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                {{ audioUploading ? '上传中...' : '将音频文件拖到此处，或' }}<em>{{ audioUploading ? '' : '点击上传' }}</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持 mp3、wav、m4a 等音频格式，文件大小不超过50MB
                </div>
              </template>
            </el-upload>
            
            <!-- 上传进度条 -->
            <div v-if="audioUploadProgress > 0 && audioUploadProgress < 100" class="upload-progress">
              <el-progress 
                :percentage="audioUploadProgress" 
                :status="audioUploadProgress === 100 ? 'success' : undefined"
                :stroke-width="8"
              />
              <div class="progress-text">上传进度: {{ audioUploadProgress }}%</div>
            </div>
            
            <!-- 音频预览 -->
            <div v-if="audioPreviewUrl" class="media-preview">
              <div class="preview-title">音频预览：</div>
              <audio :src="audioPreviewUrl" controls style="width: 100%; max-width: 500px;"></audio>
              <div class="file-actions">
                <el-button type="danger" size="small" @click="removeAudioFile">
                  删除音频
                </el-button>
              </div>
            </div>
          </div>
        </el-form-item>

        <!-- 视频上传区域 -->
        <el-form-item 
          label="视频文件" 
          prop="videoUrl"
          v-if="articleForm.type === 'video'"
        >
          <div class="upload-section">
            <el-upload
              ref="videoUploadRef"
              class="upload-demo"
              drag
              :auto-upload="false"
              :on-change="handleVideoChange"
              :before-upload="beforeVideoUpload"
              accept="video/*"
              :limit="1"
              :file-list="videoFileList"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将视频文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持 mp4、avi、mov 等视频格式，文件大小不超过200MB
                </div>
              </template>
            </el-upload>
            
            <!-- 视频预览 -->
            <div v-if="videoPreviewUrl" class="media-preview">
              <div class="preview-title">视频预览：</div>
              <video :src="videoPreviewUrl" controls style="width: 100%; max-width: 500px; height: 300px;"></video>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="文章内容" prop="content" class="content-item">
          <div class="editor-container">
            <!-- 富文本编辑器工具栏 -->
            <div class="editor-toolbar">
              <!-- 文本格式 -->
              <el-button-group>
                <el-button size="small" @click="insertBold" title="粗体 (Ctrl+B)">
                  <strong>B</strong>
                </el-button>
                <el-button size="small" @click="insertItalic" title="斜体 (Ctrl+I)">
                  <em>I</em>
                </el-button>
                <el-button size="small" @click="insertUnderline" title="下划线">
                  <u>U</u>
                </el-button>
                <el-button size="small" @click="insertStrikethrough" title="删除线">
                  <s>S</s>
                </el-button>
              </el-button-group>
              
              <!-- 标题 -->
              <el-button-group style="margin-left: 10px;">
                <el-button size="small" @click="insertHeading(1)" title="一级标题">H1</el-button>
                <el-button size="small" @click="insertHeading(2)" title="二级标题">H2</el-button>
                <el-button size="small" @click="insertHeading(3)" title="三级标题">H3</el-button>
              </el-button-group>
              
              <!-- 列表和引用 -->
              <el-button-group style="margin-left: 10px;">
                <el-button size="small" @click="insertList('unordered')" title="无序列表">
                  <el-icon><List /></el-icon>
                </el-button>
                <el-button size="small" @click="insertList('ordered')" title="有序列表">
                  <el-icon><Rank /></el-icon>
                </el-button>
                <el-button size="small" @click="insertQuote" title="引用">
                  <el-icon><ChatDotSquare /></el-icon>
                </el-button>
              </el-button-group>
              
              <!-- 链接和图片 -->
              <el-button-group style="margin-left: 10px;">
                <el-button size="small" @click="insertLink" title="链接">
                  <el-icon><Link /></el-icon>
                </el-button>
                <el-button size="small" @click="insertImage" title="图片">
                  <el-icon><Picture /></el-icon>
                </el-button>
                <el-button size="small" @click="insertCode" title="行内代码">
                  <el-icon><Document /></el-icon>
                </el-button>
                <el-button size="small" @click="insertCodeBlock" title="代码块">
                  <el-icon><DocumentCopy /></el-icon>
                </el-button>
              </el-button-group>
              
              <!-- 表格和分割线 -->
              <el-button-group style="margin-left: 10px;">
                <el-button size="small" @click="insertTable" title="表格">
                  <el-icon><Grid /></el-icon>
                </el-button>
                <el-button size="small" @click="insertHorizontalRule" title="分割线">
                  <el-icon><Minus /></el-icon>
                </el-button>
              </el-button-group>
              
              <!-- 预览和帮助 -->
              <el-button-group style="margin-left: 10px;">
                <el-button size="small" @click="togglePreview" :type="showPreview ? 'primary' : ''">
                  <el-icon><View /></el-icon>
                  {{ showPreview ? '编辑' : '预览' }}
                </el-button>
                <el-button size="small" @click="showMarkdownHelp" title="Markdown语法帮助">
                  <el-icon><QuestionFilled /></el-icon>
                </el-button>
              </el-button-group>
            </div>
            
            <!-- 编辑器内容区域 -->
            <div class="editor-content">
              <!-- 编辑模式 -->
              <el-input
                v-if="!showPreview"
                v-model="articleForm.content"
                type="textarea"
                placeholder="请输入文章内容，支持 Markdown 格式...

示例：
# 一级标题
## 二级标题
**粗体文字** *斜体文字* ~~删除线~~
> 这是引用内容
- 无序列表项
1. 有序列表项
[链接文字](http://example.com)
![图片描述](image.jpg)
`行内代码`
```
代码块
```"
                :rows="20"
                class="content-editor"
                ref="contentEditorRef"
                @keydown="handleKeydown"
              />
              
              <!-- 预览模式 -->
              <div v-else class="content-preview" v-html="renderedContent"></div>
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            提交
          </el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>

      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  UploadFilled, 
  List, 
  Rank, 
  ChatDotSquare, 
  Link, 
  Picture, 
  Document, 
  DocumentCopy, 
  Grid, 
  Minus, 
  View, 
  QuestionFilled 
} from '@element-plus/icons-vue'
import api from '@/../api/api.js'

const router = useRouter()

// 表单引用
const articleFormRef = ref()
const contentEditorRef = ref()
const audioUploadRef = ref()
const videoUploadRef = ref()

// 提交加载状态
const submitLoading = ref(false)

// 上传状态
const audioUploading = ref(false)
const audioUploadProgress = ref(0)

// 预览模式切换
const showPreview = ref(false)

// 文件列表
const audioFileList = ref([])
const videoFileList = ref([])

// 预览URL
const audioPreviewUrl = ref('')
const videoPreviewUrl = ref('')

// 文章表单数据
const articleForm = reactive({
  title: '',
  summary: '',
  type: 'text',
  content: '',
  audioUrl: '',
  videoUrl: '',
  operator: ''
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入文章简介', trigger: 'blur' },
    { min: 10, max: 300, message: '简介长度在 10 到 300 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择文章类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    { min: 50, message: '文章内容至少50个字符', trigger: 'blur' }
  ],
  operator: [
    { required: true, message: '请输入操作人姓名', trigger: 'blur' }
  ]
}

// 简单的 Markdown 渲染（增强版）
const renderedContent = computed(() => {
  let content = articleForm.content
  
  if (!content) return ''
  
  // 处理代码块（需要先处理，避免被其他规则影响）
  content = content.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, lang, code) => {
    return `<pre class="code-block ${lang || ''}"><code>${escapeHtml(code.trim())}</code></pre>`
  })
  
  // 处理行内代码
  content = content.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>')
  
  // 处理标题
  content = content.replace(/^### (.*$)/gim, '<h3>$1</h3>')
  content = content.replace(/^## (.*$)/gim, '<h2>$1</h2>')
  content = content.replace(/^# (.*$)/gim, '<h1>$1</h1>')
  
  // 处理水平分割线
  content = content.replace(/^---+$/gim, '<hr>')
  
  // 处理引用
  content = content.replace(/^> (.*$)/gim, '<blockquote>$1</blockquote>')
  
  // 处理粗体
  content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  
  // 处理斜体
  content = content.replace(/\*(.*?)\*/g, '<em>$1</em>')
  
  // 处理删除线
  content = content.replace(/~~(.*?)~~/g, '<del>$1</del>')
  
  // 处理链接
  content = content.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>')
  
  // 处理图片
  content = content.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1" style="max-width: 100%; height: auto;">')
  
  // 处理有序列表
  content = content.replace(/^\d+\. (.*$)/gim, '<li-ordered>$1</li-ordered>')
  content = content.replace(/(<li-ordered>.*<\/li-ordered>)/s, (match) => {
    return '<ol>' + match.replace(/<li-ordered>/g, '<li>').replace(/<\/li-ordered>/g, '</li>') + '</ol>'
  })
  
  // 处理无序列表
  content = content.replace(/^[*-] (.*$)/gim, '<li-unordered>$1</li-unordered>')
  content = content.replace(/(<li-unordered>.*<\/li-unordered>)/s, (match) => {
    return '<ul>' + match.replace(/<li-unordered>/g, '<li>').replace(/<\/li-unordered>/g, '</li>') + '</ul>'
  })
  
  // 处理表格
  content = content.replace(/\|(.+)\|/g, (match, row) => {
    const cells = row.split('|').map(cell => cell.trim()).filter(cell => cell)
    return '<tr>' + cells.map(cell => `<td>${cell}</td>`).join('') + '</tr>'
  })
  content = content.replace(/(<tr>.*<\/tr>)/s, '<table class="markdown-table">$1</table>')
  
  // 替换换行
  content = content.replace(/\n/g, '<br>')
  
  return content
})

// HTML转义函数
const escapeHtml = (text) => {
  const map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  }
  return text.replace(/[&<>"']/g, (m) => map[m])
}

// 音频文件处理
const handleAudioChange = (file) => {
  console.log('音频文件选择:', file)
  
  if (file.raw) {
    // 暂时创建本地预览URL，上传成功后会替换为服务器URL
    audioPreviewUrl.value = URL.createObjectURL(file.raw)
    
    // 开始上传文件
    uploadAudioFile(file.raw)
  }
}

const beforeAudioUpload = (file) => {
  const isAudio = file.type.startsWith('audio/')
  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isAudio) {
    ElMessage.error('只能上传音频文件!')
    return false
  }
  if (!isLt50M) {
    ElMessage.error('音频文件大小不能超过 50MB!')
    return false
  }
  
  // 重置上传进度
  audioUploadProgress.value = 0
  audioUploading.value = true
  
  return true
}

// 自定义音频文件上传
const uploadAudioFile = async (file) => {
  try {
    console.log('开始上传音频文件:', file.name)
    
    const formData = new FormData()
    formData.append('file', file)
    formData.append('type', 'audio')
    
    // 使用XMLHttpRequest来支持上传进度
    const xhr = new XMLHttpRequest()
    
    // 监听上传进度
    xhr.upload.addEventListener('progress', (event) => {
      if (event.lengthComputable) {
        const percentComplete = Math.round((event.loaded / event.total) * 100)
        audioUploadProgress.value = percentComplete
        console.log(`音频上传进度: ${percentComplete}%`)
      }
    })
    
    // 监听上传完成
    xhr.addEventListener('load', () => {
      audioUploading.value = false
      
      if (xhr.status === 200) {
        try {
          const response = JSON.parse(xhr.responseText)
          console.log('音频上传成功:', response)
          
          if (response.code === 0) {
            // 使用后端返回的文件URL作为音频URL
            articleForm.audioUrl = response.data?.fileUrl || ''
            
            // 更新音频文件列表，使用后端返回的文件名
            audioFileList.value = [{
              name: response.data?.fileName || file.name,
              url: articleForm.audioUrl
            }]
            
            // 清除本地预览URL，使用后端返回的URL
            if (audioPreviewUrl.value && audioPreviewUrl.value.startsWith('blob:')) {
              URL.revokeObjectURL(audioPreviewUrl.value)
            }
            audioPreviewUrl.value = response.data?.fileUrl || ''
            
            ElMessage.success('音频上传成功')
            
            // 触发表单验证
            setTimeout(() => {
              articleFormRef.value?.validateField('audioUrl')
            }, 100)
          } else {
            // 显示后端返回的错误信息
            throw new Error(response.message || '上传失败')
          }
        } catch (parseError) {
          console.error('解析响应失败:', parseError)
          ElMessage.error('上传响应解析失败')
        }
      } else {
        ElMessage.error(`上传失败，状态码: ${xhr.status}`)
      }
      
      // 重置进度
      audioUploadProgress.value = 0
    })
    
    // 监听上传错误
    xhr.addEventListener('error', () => {
      audioUploading.value = false
      audioUploadProgress.value = 0
      console.error('音频上传失败')
      ElMessage.error('音频上传失败，请检查网络连接')
    })
    
    // 监听上传中止
    xhr.addEventListener('abort', () => {
      audioUploading.value = false
      audioUploadProgress.value = 0
      console.log('音频上传已取消')
      ElMessage.info('音频上传已取消')
    })
    
    // 先打开请求，再设置请求头
    xhr.open('POST', api.otherUrl.uploadAudio)
    
    // 设置请求头（必须在open之后，send之前）
    const token = localStorage.getItem('token')
    if (token) {
      xhr.setRequestHeader('Authorization', `Bearer ${token}`)
    }
    
    // 发起上传请求
    xhr.send(formData)
    
  } catch (error) {
    audioUploading.value = false
    audioUploadProgress.value = 0
    console.error('音频上传异常:', error)
    ElMessage.error('音频上传失败，请稍后重试')
  }
}

// 删除音频文件
const removeAudioFile = () => {
  articleForm.audioUrl = ''
  audioFileList.value = []
  audioPreviewUrl.value = ''
  audioUploadProgress.value = 0
  
  // 清空上传组件
  if (audioUploadRef.value) {
    audioUploadRef.value.clearFiles()
  }
  
  ElMessage.success('音频文件已删除')
  
  // 触发表单验证
  setTimeout(() => {
    articleFormRef.value?.validateField('audioUrl')
  }, 100)
}

// 视频文件处理
const handleVideoChange = (file) => {
  console.log('视频文件选择:', file)
  
  if (file.raw) {
    // 创建预览URL
    videoPreviewUrl.value = URL.createObjectURL(file.raw)
    articleForm.videoUrl = file.name
    
    // 这里可以实现实际的文件上传逻辑
    // uploadVideoFile(file.raw)
  }
}

const beforeVideoUpload = (file) => {
  const isVideo = file.type.startsWith('video/')
  const isLt200M = file.size / 1024 / 1024 < 200

  if (!isVideo) {
    ElMessage.error('只能上传视频文件!')
    return false
  }
  if (!isLt200M) {
    ElMessage.error('视频文件大小不能超过 200MB!')
    return false
  }
  return true
}

// 富文本编辑器功能（增强版）
const insertBold = () => {
  insertTextAtCursor('**', '**')
}

const insertItalic = () => {
  insertTextAtCursor('*', '*')
}

const insertUnderline = () => {
  insertTextAtCursor('<u>', '</u>')
}

const insertStrikethrough = () => {
  insertTextAtCursor('~~', '~~')
}

const insertHeading = (level = 2) => {
  const prefix = '#'.repeat(level) + ' '
  insertTextAtLineStart(prefix)
}

const insertList = (type = 'unordered') => {
  if (type === 'ordered') {
    insertTextAtLineStart('1. ')
  } else {
    insertTextAtLineStart('- ')
  }
}

const insertQuote = () => {
  insertTextAtLineStart('> ')
}

const insertLink = () => {
  insertTextAtCursor('[链接文字](', ')')
}

const insertImage = () => {
  insertTextAtCursor('![图片描述](', ')')
}

const insertCode = () => {
  insertTextAtCursor('`', '`')
}

const insertCodeBlock = () => {
  insertTextAtCursor('\n```\n', '\n```\n')
}

const insertTable = () => {
  const tableText = `
| 列1 | 列2 | 列3 |
|-----|-----|-----|
| 内容1 | 内容2 | 内容3 |
| 内容4 | 内容5 | 内容6 |
`
  insertTextAtCursor(tableText, '')
}

const insertHorizontalRule = () => {
  insertTextAtCursor('\n---\n', '')
}

// 在光标处插入文本
const insertTextAtCursor = (before, after) => {
  const textarea = getTextarea()
  if (textarea) {
    const start = textarea.selectionStart
    const end = textarea.selectionEnd
    const selectedText = articleForm.content.substring(start, end)
    
    const newText = before + selectedText + after
    articleForm.content = articleForm.content.substring(0, start) + newText + articleForm.content.substring(end)
    
    // 设置光标位置
    setTimeout(() => {
      textarea.focus()
      const newPosition = start + before.length + selectedText.length
      textarea.setSelectionRange(newPosition, newPosition)
    }, 0)
  }
}

// 在行首插入文本
const insertTextAtLineStart = (text) => {
  const textarea = getTextarea()
  if (textarea) {
    const start = textarea.selectionStart
    const content = articleForm.content
    
    // 找到当前行的开始位置
    let lineStart = start
    while (lineStart > 0 && content[lineStart - 1] !== '\n') {
      lineStart--
    }
    
    // 插入文本
    articleForm.content = content.substring(0, lineStart) + text + content.substring(lineStart)
    
    // 设置光标位置
    setTimeout(() => {
      textarea.focus()
      const newPosition = start + text.length
      textarea.setSelectionRange(newPosition, newPosition)
    }, 0)
  }
}

// 获取textarea元素
const getTextarea = () => {
  return contentEditorRef.value?.textarea || contentEditorRef.value?.$refs?.textarea
}

// 键盘快捷键处理
const handleKeydown = (event) => {
  if (event.ctrlKey || event.metaKey) {
    switch (event.key) {
      case 'b':
        event.preventDefault()
        insertBold()
        break
      case 'i':
        event.preventDefault()
        insertItalic()
        break
      case 'k':
        event.preventDefault()
        insertLink()
        break
      case 'Enter':
        event.preventDefault()
        insertCodeBlock()
        break
    }
  }
}

// 显示Markdown帮助
const showMarkdownHelp = () => {
  ElMessageBox.alert(`
<div style="text-align: left;">
<h3>Markdown 语法帮助</h3>

<h4>标题</h4>
<code># 一级标题</code><br>
<code>## 二级标题</code><br>
<code>### 三级标题</code>

<h4>文本格式</h4>
<code>**粗体**</code><br>
<code>*斜体*</code><br>
<code>~~删除线~~</code><br>
<code>\`行内代码\`</code>

<h4>列表</h4>
<code>- 无序列表</code><br>
<code>1. 有序列表</code>

<h4>链接和图片</h4>
<code>[链接文字](URL)</code><br>
<code>![图片描述](图片URL)</code>

<h4>其他</h4>
<code>> 引用</code><br>
<code>--- (分割线)</code><br>
<code>\`\`\` (代码块)</code>

<h4>快捷键</h4>
<code>Ctrl+B: 粗体</code><br>
<code>Ctrl+I: 斜体</code><br>
<code>Ctrl+K: 链接</code><br>
<code>Ctrl+Enter: 代码块</code>
</div>
  `, 'Markdown 语法帮助', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '知道了'
  })
}

const togglePreview = () => {
  showPreview.value = !showPreview.value
}

// 表单提交
const handleSubmit = async () => {
  try {
    const valid = await articleFormRef.value.validate()
    if (valid) {
      submitLoading.value = true
      
      console.log('提交文章数据:', articleForm)
      
      // 这里实现实际的提交逻辑
      // const response = await submitArticle(articleForm)
      // if (response.code === 0) {
      //   ElMessage.success('文章创建成功!')
      //   router.push({ name: 'content' })
      // } else {
      //   ElMessage.error(response.message || '创建失败')
      // }
      
      // 模拟提交成功
      await new Promise(resolve => setTimeout(resolve, 1000))
      ElMessage.success('文章创建成功!')
      router.push({ name: 'content' })
    }
  } catch (error) {
    console.log('表单验证失败:', error)
    ElMessage.error('请检查表单内容')
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const handleReset = () => {
  articleFormRef.value?.resetFields()
  
  // 清除文件
  audioFileList.value = []
  videoFileList.value = []
  audioPreviewUrl.value = ''
  videoPreviewUrl.value = ''
  
  // 清除上传组件
  audioUploadRef.value?.clearFiles()
  videoUploadRef.value?.clearFiles()
  
  ElMessage.info('表单已重置')
}

// 返回列表
const goBack = () => {
  router.push({ name: 'content' })
}
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.form-card {
  margin-bottom: 20px;
}

.article-form {
  max-width: 1000px;
}

.upload-section {
  width: 100%;
}

.media-preview {
  margin-top: 15px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.preview-title {
  margin-bottom: 10px;
  font-weight: bold;
  color: #606266;
}

.file-actions {
  margin-top: 10px;
  text-align: right;
}

.upload-progress {
  margin-top: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.progress-text {
  margin-top: 8px;
  font-size: 12px;
  color: #606266;
  text-align: center;
}

.editor-container {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.editor-toolbar {
  padding: 10px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 5px;
}

.editor-toolbar .el-button-group {
  margin-right: 5px;
}

.editor-content {
  min-height: 400px;
}

.content-editor {
  border: none !important;
}

.content-editor :deep(.el-textarea__inner) {
  border: none !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
  font-size: 14px;
  line-height: 1.6;
  tab-size: 4;
}

.content-preview {
  padding: 20px;
  min-height: 400px;
  line-height: 1.8;
  font-size: 14px;
  color: #333;
  overflow-y: auto;
}

.content-preview h1 {
  font-size: 28px;
  margin: 20px 0 15px 0;
  color: #2c3e50;
  border-bottom: 2px solid #eaecef;
  padding-bottom: 10px;
}

.content-preview h2 {
  font-size: 24px;
  margin: 18px 0 12px 0;
  color: #34495e;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 8px;
}

.content-preview h3 {
  font-size: 20px;
  margin: 15px 0 10px 0;
  color: #5a6c7d;
}

.content-preview ul, .content-preview ol {
  margin: 15px 0;
  padding-left: 25px;
}

.content-preview li {
  margin: 8px 0;
  line-height: 1.6;
}

.content-preview a {
  color: #409eff;
  text-decoration: none;
  border-bottom: 1px solid transparent;
  transition: border-color 0.3s;
}

.content-preview a:hover {
  border-bottom-color: #409eff;
}

.content-preview blockquote {
  margin: 15px 0;
  padding: 10px 15px;
  background-color: #f8f9fa;
  border-left: 4px solid #409eff;
  color: #666;
}

.content-preview hr {
  margin: 20px 0;
  border: none;
  border-top: 2px solid #eaecef;
}

.content-preview .inline-code {
  background-color: #f1f2f6;
  color: #e74c3c;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
  font-size: 13px;
}

.content-preview .code-block {
  background-color: #f8f9fa;
  border: 1px solid #e1e8ed;
  border-radius: 6px;
  padding: 15px;
  margin: 15px 0;
  overflow-x: auto;
}

.content-preview .code-block code {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
  font-size: 13px;
  line-height: 1.5;
  color: #333;
  background: none;
}

.content-preview .markdown-table {
  border-collapse: collapse;
  margin: 15px 0;
  width: 100%;
  border: 1px solid #ddd;
}

.content-preview .markdown-table td {
  border: 1px solid #ddd;
  padding: 8px 12px;
  text-align: left;
}

.content-preview .markdown-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.content-preview img {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 10px 0;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.content-item :deep(.el-form-item__content) {
  line-height: normal;
}
</style>
